package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Override
    @Transactional
    public AddressBook changeUpdateDefaultAddressBook(Long id, Long userId) {
        //找出原默认地址
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId).eq(AddressBook::getIsDefault,1);
        AddressBook oldAddressBook=this.getOne(queryWrapper);
        //判断是否存在默认地址
        if(oldAddressBook != null){
            //取消原默认地址
            oldAddressBook.setIsDefault(0);
            this.updateById(oldAddressBook);
        }
        //根据地址id查找地址
        AddressBook addressBook=this.getById(id);
        //设置地址为默认
        addressBook.setIsDefault(1);
//        System.out.println("更新前"+BaseContext.getThreadLocal());
        this.updateById(addressBook);

        return addressBook;
    }

    @Override
    @Transactional
    public Boolean deleteAddressBook(Long id) {
        //判断是否为默认地址
        AddressBook addressBook=this.getById(id);
        boolean flag=this.removeById(id);
        if(addressBook.getIsDefault() == 1){
            //如果是默认地址 则获取该用户的地址列表
            LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AddressBook::getUserId,addressBook.getUserId());
            List<AddressBook> list=this.list(queryWrapper);
            //判断 是否存在其他地址 如果 存在 则设置第一个为默认地址
            if (list !=null){
                list.get(0).setIsDefault(1);
                this.updateById(list.get(0));
            }
        }
        //刪除地址
        return flag;
    }

    @Override
    public AddressBook getDefaultAddressBook(Long userId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,userId).eq(AddressBook::getIsDefault,1);
        AddressBook addressBook=this.getOne(queryWrapper);
        return addressBook;
    }
}
